#include "myserialport.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>

MySerialPort::MySerialPort(QObject *parent) : QObject(parent)
{
    port = new QSerialPort;
    port->setDataBits(QSerialPort::Data8);
    port->setStopBits(QSerialPort::OneStop);
    port->setFlowControl(QSerialPort::NoFlowControl);
    port->setParity(QSerialPort::NoParity);

    connect(port, &QSerialPort::readyRead,
            this, &MySerialPort::portReadyReadSlot);
}

MySerialPort::~MySerialPort()
{
    closeSerialPort();
}

bool MySerialPort::openSerialPort(QString portName, quint16 baudRate)
{
    port->setPortName(portName);
    port->setBaudRate(baudRate);
    return port->open(QIODevice::ReadWrite);
}

void MySerialPort::closeSerialPort()
{
    if(port->isOpen()){
        port->flush();
        port->close();
    }
}

QStringList MySerialPort::getSerialPortList()
{
    QStringList list;
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        list.append(info.portName());
    }
    return list;
}

bool MySerialPort::getSerialPortState()
{
    return port->isOpen();
}

void MySerialPort::sendData(const QByteArray &data)
{
    if(port->isOpen())
        port->write(data);
}

void MySerialPort::portReadyReadSlot()
{
    QByteArray data;
    while (port->bytesAvailable()) {
        data.append(port->readAll());
    }
    emit receiveData(port->portName(), data);
}
